﻿using AllInOne.Classes;
using AllInOne.HDI.CRT_591_M001;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AllInOne.MainPages
{
    /// <summary>
    /// 读取二维码
    /// </summary>
    public partial class ReadQR_Code : Window
    {
        internal int AuthType;
        internal string AuthCode;
        AuthViewModel viewModel = new AuthViewModel() { IDCardMsg = "读取二维码", CountDown = Classes.SystemParam.CountDownReadQR_Code };
        public ReadQR_Code()
        {
            InitializeComponent();
            TbAuthCode.Focus();
            DataContext = viewModel;
        }

        readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            TbAuthCode.Text = "";
            AuthCode = "";
            Cpb.Maximum = viewModel.CountDown;
            CancellationToken token = tokenSource.Token;
            //提示弹框
            Task countTask = new Task(() =>
            {
                while (true)
                {
                    if (!token.IsCancellationRequested)
                    {
                        viewModel.CountDown--;
                        if (viewModel.CountDown == 0)
                            QuitView(false);
                        Thread.Sleep(1000);
                    }
                    else
                        return;
                }
            }, token);
            countTask.Start();

            //扫码--提示语音
            Task taskTip = new Task(() =>
            {
                VoiceHelper.Speak("请展示二维码");
            }, token);
            taskTip.Start();
        }

        private void QuitView(bool result)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                tokenSource.Cancel();
                this.DialogResult = result;
                this.Close();
            }));
        }

        private void BdQuit_Click(object sender, RoutedEventArgs e)
        {
            QuitView(false);
        }

        private void TbAuthCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && TbAuthCode.Text.Length > 0)
            {
                //表示拿到了二维码信息
                AuthType = 0;
                AuthCode = TbAuthCode.Text;
                TbAuthCode.Text = "";
                Log.Info($"二维码：{AuthCode}");
                QuitView(true);
            }
        }
    }
}
